import axios from 'axios';
import {Message} from 'element-ui';
import router from '../router/index';

const baseUrl = process.env.NODE_ENV === 'production' ? '/' : '/api';

const service = axios.create({
    baseURL: baseUrl, // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 80000 // request timeout
});

service.interceptors.request.use(
    config => {
        /**
         *处理浏览器缓存
         */
        let url = config.url;
        if (url.indexOf('?') > 0) {
            url = `${url}&_time=${new Date().getTime()}`;
        } else {
            url = `${url}?_time=${new Date().getTime()}`;
        }
        config.url = url;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
service.interceptors.response.use(
    res => {
        if (res.request && res.request.responseType == "blob") {
            return res;
        } else {
            return res.data;
        }
    },
    error => {
        if (/timeout\sof\s\d+ms\sexceeded/.test(error.message)) {
            // 超时
            Message.error('请求超时，请稍后重试！');
        }
        if (error.response) {
            // http状态码判断
            switch (error.response.status) {
                // http status handler
                case 401:
                    router.replace({
                        path: '/login'
                    });
                    break;
                case 404:
                    Message.error('请求的资源不存在！');
                    break;
                case 500:
                    Message.error('内部错误，请稍后重试！');
                    break;
                case 503:
                    Message.error('服务器正在维护，请稍等！');
                    break;
            }
        }
        return Promise.reject(error.response);
    }
);

service.download = (url, method, data) => {
    service.request({
        url: url,
        method: method,
        params: data.params,
        data: data.data,
        responseType: 'blob'
    }).then(res => {
        const blob = new Blob([res.data]);
        const disposition = res.headers['content-disposition'];
        let fileName = disposition.substring(disposition.indexOf('filename=') + 9, disposition.length);
        fileName = decodeURI(fileName);
        const elink = document.createElement('a');
        if ('download' in elink) { // 非IE下载
            elink.download = fileName;
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink)
        } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
        }
    }).catch(err => {
        console.log(err);
        Message.error("文件下载失败");
    });
};

export default {
    install(Vue, option) {
        Vue.prototype.$axios = service;
    },
    service
}
